
#include "bsp_delay.h"

/**
 * @brief     延迟函数us
 *
 * @param us  延迟时间
 */
void delay_us(unsigned long us) {
  GPT_Init(GPT1, 65, 0xffffffff, 0);
  GPT_Enabled(GPT1);
  unsigned long old_cnt = 0;
  unsigned long new_cnt = 0;
  unsigned long tcnt_value = 0;
  old_cnt = GPT1->CNT;
  while (1) {
    new_cnt = GPT1->CNT;
    if (new_cnt != old_cnt) {
      if (new_cnt > old_cnt) {
        tcnt_value += new_cnt - old_cnt;
      } else {
        tcnt_value += 0xffffffff - old_cnt + new_cnt;
      }
      old_cnt = new_cnt;
      if (tcnt_value >= us) {
        break;
      }
    }
  }
}

/**
 * @brief     延迟函数ms
 *
 * @param us  延迟时间ms
 */
void delay_ms(unsigned long ms) { delay_us(ms * 1000); }

/**
 * @brief     延迟函数s
 *
 * @param us  延迟时间s
 */
void delay_s(unsigned int s) { delay_ms(s * 1000); }

#if 0
void delay_init() {
  GPT_Init(GPT1, 65, 500000, 0);
  GPT_GIC_EnableIRQ(GPT1_IRQn);
  GPT_IRQ_Handler(GPT1_IRQn, GPT1_IRQHandler, NULL);
  GPT_IR(GPT1, 0);
  GPT_Enabled(GPT1);
}

void GPT1_IRQHandler(unsigned int giccIar, void *param) {
  static u8 state = 0;
  if ((GPT1->SR) & 0x1) {
    state = !state;
    beep_switch(LED0, state);
  }
  GPT1->SR |= 0x1;
}

#endif